package com.hslxy.niukewang.controller;

import com.alibaba.fastjson2.JSONObject;
import com.hslxy.niukewang.component.Page;
import com.hslxy.niukewang.entity.Message;
import com.hslxy.niukewang.entity.User;
import com.hslxy.niukewang.service.MessageService;
import com.hslxy.niukewang.service.UserService;
import com.hslxy.niukewang.util.CommunityUtil;
import com.hslxy.niukewang.util.Constant;
import com.hslxy.niukewang.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController implements Constant {
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;

    @RequestMapping(path = "/letter/list", method = RequestMethod.GET)
    public String getLetterList(Model model, Page page){
        User user = hostHolder.getUsers();
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));
        List<Message> conversations = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());
        int unreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (conversations != null){
            for (Message message:conversations){
                Map<String, Object> map = new HashMap<>();
                int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), message.getConversationId());
                map.put("message", message);
                map.put("letterUnreadCount", letterUnreadCount);
                int targetId = message.getFromId() != user.getId()? message.getFromId():message.getToId();
                map.put("targetUser", userService.findUserById(targetId));
                int letterCount = messageService.findLetterCount(message.getConversationId());
                map.put("letterCount", letterCount);
                mapList.add(map);
            }
        }
        model.addAttribute("mapList", mapList);
        model.addAttribute("unreadCount", unreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "/site/letter";
    }

//    读取私信详情
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @RequestMapping(value = "/letter/detail/{conversationId}", method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Model model, Page page){
        User user = hostHolder.getUsers();
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.findLetterCount(conversationId));
        List<Message> letters = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (letters!=null){
            for (Message letter :
                    letters) {
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                User userById = userService.findUserById(letter.getFromId());
                stringObjectHashMap.put("user", userById);
                stringObjectHashMap.put("letter", letter);
                mapList.add(stringObjectHashMap);
            }
        }
        String[] split = conversationId.split("_");
        int targetId =  Integer.parseInt(split[0]) != user.getId()? Integer.parseInt(split[0]):Integer.parseInt(split[1]);
        model.addAttribute("targetUser", userService.findUserById(targetId));
        model.addAttribute("mapList", mapList);

//        设置已读
        List<Integer> unreadLetterIds = messageService.getUnreadLetterIds(letters, user);
        if(!unreadLetterIds.isEmpty())
            messageService.readMessage(unreadLetterIds);
        return "/site/letter-detail";
    }

    @RequestMapping(value = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content){
        User targetUser = userService.findByName(toName);
        if(targetUser == null){
            return CommunityUtil.getJSONString(1 , "目标用户不存在");
        }
        Message message = new Message();
        message.setContent(content);
        User users = hostHolder.getUsers();
        message.setFromId(users.getId());
        message.setCreateTime(new Date());
        message.setToId(targetUser.getId());
        String conversationId = message.getFromId() > message.getToId()?message.getToId()+"_"+message.getFromId():message.getFromId()+"_" + message.getToId();
        message.setConversationId(conversationId);
        messageService.addMessage(message);
        return CommunityUtil.getJSONString(0);
    }


    @RequestMapping(value = "/letter/delete", method = RequestMethod.POST)
    @ResponseBody
    public String deleteLetter(int id){
        messageService.deleteMessage(id);
        return CommunityUtil.getJSONString(0);
    }

    @RequestMapping(path = "/notice/list", method = RequestMethod.GET)
    public String getNoticeList(Model model){
        User user = hostHolder.getUsers();
        Message comment = messageService.findLatestNotice(user.getId(), TOPIC_COMMENT);
        if(comment != null){
            HashMap<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", comment);
            String content = HtmlUtils.htmlUnescape(comment.getContent());
//            {"entityType":1,"entityId":280,"postId":280,"userId":149}
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));
            int commentCount = messageService.findNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("count",commentCount);
            int commentUnreadCount = messageService.findNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("unreadCount",commentUnreadCount);
            model.addAttribute("comment", messageVO);
        }


        Message follow = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);
        if(follow != null){
            HashMap<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", follow);
            String content = HtmlUtils.htmlUnescape(follow.getContent());
//            {"entityType":1,"entityId":280,"postId":280,"userId":149}
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            int followCount = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("count",followCount);
            int followUnreadCount = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unreadCount",followUnreadCount);
            model.addAttribute("follow", messageVO);
        }


        Message like = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);

        if(like != null){
            HashMap<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", like);
            String content = HtmlUtils.htmlUnescape(like.getContent());
//            {"entityType":1,"entityId":280,"postId":280,"userId":149}
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));
            int likeCount = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("count",likeCount);
            int likeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unreadCount",likeUnreadCount);
            model.addAttribute("like", messageVO);
        }

        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        model.addAttribute("letterUnreadCount",letterUnreadCount);

        return "/site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model){
        User users = hostHolder.getUsers();
        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(users.getId(), topic));
        List<Message> notices = messageService.findNotices(users.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String, Object>> noticeList = new ArrayList<>();
        if(notices != null){
            for(Message notice: notices){
                Map<String, Object> map = new HashMap<>();
                map.put("notice", notice);
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userService.findUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                // 通知作者
                map.put("fromUser", userService.findUserById(notice.getFromId()));

                noticeList.add(map);
            }
        }
        model.addAttribute("notices", noticeList);

        // 设置已读
        List<Integer> ids = messageService.getUnreadLetterIds(notices, users);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
        return "/site/notice-detail";
    }
}
